<template>
  <el-card class="box-card" shadow="never">
    <div class="box-card-title">周报压缩包上传</div>
    <el-upload
        class="upload-demo"
        drag
        multiple
        :show-file-list="true"
        :limit="excelLimit"
        :http-request="uploadExcel"
        :before-upload="beforeExcelUpload"
        :on-exceed="handleExceed"
        :on-success="excelUploadSuccess"
        :on-error="excelUploadError"
        :on-progress="handleProgress"
        accept=".zip"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处<em>或点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">请上传 .zip 标准格式文件</div>
      </template>
    </el-upload>
    <el-progress v-if="uploadProgress.show" :percentage="uploadProgress.percentage" />
  </el-card>

</template>

<script setup>import { ref } from 'vue'
import { ElNotification } from 'element-plus'
import axios from "axios";

// 添加上传进度状态
const uploadProgress = ref({
  show: false,
  percentage: 0,
})

// 更新上传进度的处理函数
const handleProgress = (event, file) => {
  console.log('Progress event triggered:', event, 'File:', file);
  uploadProgress.value.show = true
  uploadProgress.value.percentage = Math.floor(event.percent)
}


// 在上传成功或失败后隐藏进度条
const hideProgress = () => {
  uploadProgress.value.show = false
  uploadProgress.value.percentage = 0
}

// 最大文件数
const excelLimit = ref(1)

// 文件上传
const uploadExcel = async (file) => {
  try {

    if (!file) {
      throw new Error('File is missing'); // 显式抛出错误，便于调试
    }

    const formData = new FormData();

    formData.append('file', file.file,file.file.name);




    excelUploadSuccess(); // 成功后调用通知
  } catch (error) {
    console.error('文件上传失败', error);
    if (error.response) {
      // 后端返回的错误
      ElNotification({
        message: error.response.data.message || '文件上传失败，请检查文件格式和大小',
        type: 'error',
      });
    } else {
      // 网络错误或其他未知错误
      ElNotification({
        message: '网络错误，请稍后再试',
        type: 'error',
      });
    }
  }
}


// 文件数超出提示
const handleExceed = (file) => {
  ElNotification({
    message: '最多只能上传一个文件！',
    type: 'warning',
  })
}

// 上传错误提示
const excelUploadError = (file) => {
  hideProgress()
  ElNotification({
    message: '导入数据失败，请您重新上传！',
    type: 'error',
  })
}

// 上传成功提示
const excelUploadSuccess = (file) => {
  hideProgress()
  ElNotification({
    message: '导入数据成功！',
    type: 'success',
  })
}



</script>

<style lang="scss" scoped>
.box-card {
  width: 100%;
  .box-card-title {
    padding-bottom: 20px;
  }
}
.upload-demo {
  width: 50%;
}
</style>
